package com.kedacom.demo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CookieServlet
 */
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String ecoding = "UTF-8";
		request.setCharacterEncoding(ecoding);  
		response.setCharacterEncoding(ecoding);
		response.setContentType("html/text;charset="+ecoding);
		
		Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
		if(null!=cookies){
			for(Cookie cookie : cookies){
				System.out.println(cookie.getName()+':'+cookie.getValue());
			}
		}
		
		String token = request.getParameter("token");
		String callback = request.getParameter("callback");//jquery调用方式需要回调方法
		
		//写入新的token到Cookie
		Cookie cookie = new Cookie("token",token);
		cookie.setMaxAge(3600);
		cookie.setPath("/");
		response.addCookie(cookie);
		
		System.out.println("token:"+token);
		
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(callback+"({success:true});");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}
